//
//  WSDatePickerView.m
//  WSDatePicker
//
//  Created by iMac on 17/2/23.
//  Copyright © 2017年 zws. All rights reserved.
//

#import "EKCalendarView.h"
#import "UIView+Addition.h"
#import "NSDate+ROCaculateTime.h"
#import "RODateHelper.h"
#import "NSDate+Extension.h"
#import "FSCalendar.h"

#define kScreenWidth     [UIScreen mainScreen].bounds.size.width
#define kScreenHeight    [UIScreen mainScreen].bounds.size.height
#define kPickerSize      self.datePicker.frame.size
#define RGBA(r, g, b, a) ([UIColor colorWithRed:(r / 255.0) green:(g / 255.0) blue:(b / 255.0) alpha:a])
#define RGB(r, g, b)     RGBA(r,g,b,1)

#define MAXYEAR 2020
#define MINYEAR 2015
#define kROWNUMBER 10

typedef void(^doneBlock)(NSDate *);

@interface EKCalendarView ()<UIGestureRecognizerDelegate,FSCalendarDataSource,FSCalendarDelegate> {
    NSDate *_startDate;
    EKCalendarPosition datePosition;
}
@property (weak, nonatomic) IBOutlet UIView             *containerView   ;
@property (weak, nonatomic) IBOutlet FSCalendar        *calendarView;
@property (weak, nonatomic) IBOutlet UIButton           *doneBtn         ;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftConstraint  ;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightConstraint ;

// 确认按钮点击
- (IBAction)doneAction:(UIButton *)btn;
@property (nonatomic,  copy) doneBlock doneBlock;
@property (nonatomic,  copy) CalendarDismissBlock dBlock;

@end

@implementation EKCalendarView

-(instancetype)initWithDatePosition:(EKCalendarPosition)position CompleteBlock:(void(^)(NSDate *))completeBlock {
    
    self = [super init];
    if (self) {
        self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] lastObject];
        datePosition   = position;
        [self setupUI];
        
        if (completeBlock) {
            self.doneBlock = ^(NSDate *startDate) {
                completeBlock(startDate);
            };
        }
    }
    return self;
}

-(void)setupUI {
    self.calendarView.delegate = self;
    self.calendarView.dataSource = self;
    
    self.containerView.layer.cornerRadius  = 10;
    self.containerView.layer.masksToBounds = YES;
    self.themeColor = RGB(247, 133, 51);
    self.frame      = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    
    switch (datePosition) {
        case 0:
            
            break;
        case 1:{
            self.leftConstraint.constant  = 16;
            self.rightConstraint.constant = 16;
        }
            break;
        default:
            break;
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismiss)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
    
    self.bottomConstraint.constant = -self.height;
    [self layoutIfNeeded];
    
    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self];
}


#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if( [touch.view isDescendantOfView:self.containerView]) {
        return NO;
    }
    return YES;
}

#pragma mark - Action
-(void)show {
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    if (datePosition == EKCalendarMiddel) {
        [UIView animateWithDuration:.3 animations:^{
            self.bottomConstraint.constant = kScreenHeight / 2 - self.calendarView.height / 2;
            //NSLog(@"%f %f %f",self.bottomConstraint.constant, kScreenHeight, self.height);
            self.backgroundColor = RGBA(0, 0, 0, 0.4);
             [self layoutIfNeeded];
        }];
    }
    if (datePosition == EKCalendarBottom) {
        [UIView animateWithDuration:.3 animations:^{
            self.bottomConstraint.constant = 10;
            self.backgroundColor = RGBA(0, 0, 0, 0.4);
            [self layoutIfNeeded];
        }];
    }
}

-(void)dismiss {
    if (_dBlock) {
        _dBlock(YES);
    }
    [self hiddenAniimation];
}

- (void)dismissHandler:(CalendarDismissBlock)handler{
    _dBlock = handler;
}

-(void)hiddenAniimation{
    [UIView animateWithDuration:.3 animations:^{
        self.bottomConstraint.constant = -self.height;
        self.backgroundColor = RGBA(0, 0, 0, 0);
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self removeFromSuperview];
    }];

}

- (IBAction)doneAction:(UIButton *)btn {

    self.doneBlock(_startDate);
    [self dismiss];
}
#pragma mark - 日历代理
- (NSDate *)minimumDateForCalendar:(FSCalendar *)calendar {
    NSTimeInterval minYearTime = -365 * 24 * 60 * 60;
    NSDate *todayDate = [NSDate date];
    NSDate *oneYearFromToday = [todayDate dateByAddingTimeInterval:minYearTime];
    return oneYearFromToday;
}

-(NSDate *)maximumDateForCalendar:(FSCalendar *)calendar {
    NSTimeInterval maxYearTime = -1 * 24 * 60 * 60;
    NSDate *todayDate = [NSDate date];
    NSDate *twoYearsFromToday = [todayDate dateByAddingTimeInterval:maxYearTime];
    return twoYearsFromToday;
}

-(void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    _startDate = date;
}

@end
